﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ODP.Model;
using ODP.Com;
using ODP.Enum;

namespace ODP.SinaCrawler
{
    public partial class Login : Form
    {
        private WebBrowser webBrowser = new WebBrowser();
        
        private MainForm m_OwnerForm;

        public Login()
        {
            InitializeComponent();
            webBrowser = webBrowser1;

            btnlogin.Enabled = false;

            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
        }

        void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser.ReadyState == WebBrowserReadyState.Complete)
            {
                if (!Current.IsLogon)
                {
                    if (webBrowser.Url.ToString().Contains("www.baidu.com") && webBrowser.Url.ToString().Contains("code="))
                    {
                        //获取verify
                        ODP.Com.Current.OAuth.verify = Helper.GetQueryString(webBrowser.Url.Query, "code");

                        string requestString = "";
                        string request_Url = "";

                        List<QueryStringParameter> parameters = new List<QueryStringParameter>();

                        parameters.Add(new QueryStringParameter("grant_type", "authorization_code"));
                        parameters.Add(new QueryStringParameter("client_secret", Current.OAuth.customSecret));

                        Current.OAuth.GetOauthUrl(Current.OAuth.Access_token_url, HttpMethod.POST.ToString(), parameters, out requestString, out request_Url);
                        string result = new SyncHttp().HttpPost(request_Url, requestString);


                        Current.OAuth.tokenKey = ODP.Helper.JsonHelper.GetValueByName(result, "access_token");
                        Current.OAuth.Uid = ODP.Helper.JsonHelper.GetValueByName(result, "uid");

                        btnlogin.Enabled = false;

                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }

                    btnlogin.Enabled = true;
                }
                else
                {
                    btnlogin.Enabled = false;
                }
            }
        }

        private void Login_Load(object sender, EventArgs e)
        {
            if (this.Owner != null)
            {
                m_OwnerForm = this.Owner as MainForm;
            }


            //设置webBrowser的url,进行身份验证请求
            ODP.SinaAPI.SinaOAuth Qoa = new ODP.SinaAPI.SinaOAuth();
            Qoa.callbackUrl = "http://www.baidu.com";
            ODP.Com.Current.OAuth = Qoa;
            Qoa.customKey = m_OwnerForm.AppKey;
            Qoa.customSecret = m_OwnerForm.AppSecret;

            

            //出现输入帐号密码界面
            webBrowser.Url = new Uri("https://api.weibo.com/oauth2/authorize?client_id=" + Qoa.customKey + "&redirect_uri=" + Qoa.callbackUrl + "&response_type=code");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(this.tbname.Text))
            {
                this.lbMessage.Text = "用户名不能为空!";
                return;
            }

            if(string.IsNullOrEmpty(this.tbpassword.Text))
            {
                this.lbMessage.Text = "密码不能为空!";
                return;
            }

            AutoLogin(this.tbname.Text, this.tbpassword.Text);

        }


        private void AutoLogin(string strUserID, string strPWD)
        {
            webBrowser.Document.GetElementById("userId").SetAttribute("value", strUserID);
            webBrowser.Document.GetElementById("passwd").SetAttribute("value", strPWD);
            HtmlElement element = webBrowser.Document.GetElementById("login_btn");
            if (element != null)
            {
                element.InvokeMember("click");
            }
            else
            {
                HtmlElementCollection elements = webBrowser.Document.GetElementsByTagName("a");
                foreach (HtmlElement item in elements)
                {
                    if (item.GetAttribute("innerText") == "连接" || item.GetAttribute("innerText") == "登录并授权")
                    {
                        item.InvokeMember("click");
                        break;
                    }
                }
            }

        }

    }
}
